package org.aplombh.java.utils.rgprc;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class RandomGetUtils {
    public static Topic getRandomByWeight(List<? extends Topic> topic) {
        int[] array = new int[topic.size()];
        Random random = new Random();
        int sum = 0;
        for (int i = 0; i < topic.size(); i++) {
            sum += topic.get(i).getWeight();
            array[i] = sum;
        }

        int randomNum = random.nextInt(array[array.length - 1]) + 1;
        int left = 0, right = array.length - 1;
        while (left < right) {
            int middle = left + right >> 1;
            if (array[middle] == randomNum)
                return topic.get(middle);
            else if (array[middle] > randomNum)
                right = middle;
            else
                left = middle + 1;
        }
        return topic.get(left);
    }

    public static List<Topic> getRandomByWeight(List<? extends Topic> topic, int n) {
        int[] array = new int[topic.size()];
        Random random = new Random();
        int sum = 0;
        for (int i = 0; i < topic.size(); i++) {
            sum += topic.get(i).getWeight();
            array[i] = sum;
        }

        ArrayList<Topic> topics = new ArrayList<>();
        for (int i = 0; i < n; ) {
            int randomNum = random.nextInt(array[array.length - 1]) +1;
            int left = 0, right = array.length - 1;
            while (left < right) {
                int middle = left + right >> 1;
                if (array[middle] == randomNum) {
                    if (!topics.contains(topic.get(middle))) {
                        i++;
                        topics.add(topic.get(middle));
                    }
                    break;
                } else if (array[middle] > randomNum)
                    right = middle;
                else
                    left = middle + 1;
            }
            if (!topics.contains(topic.get(left))) {
                i++;
                topics.add(topic.get(left));
            }
        }
        return topics;
    }
}
